package com.gxsf.wechatbook.controller;

import com.gxsf.wechatbook.pojo.*;
import com.gxsf.wechatbook.repo.*;
import com.gxsf.wechatbook.util.DateUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;

/**
 * @author BlueStar http://www.bluestardt.com
 * @version 1.0.0
 * @date 2021/1/19 12:05
 */
@Component
@Api(tags = "token 实时更新，【核心代码】")
@Slf4j
public class TokenController {
    @Autowired
    TokenListRepository tokenListRepository;
    @Autowired
    ReserUserInfoRepository reserUserInfoRepository;
    @Autowired
    ReserListRepository reserListRepository;
    @Autowired
    LibraryListRepository libraryListRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    UserSmsListRepository userSmsListRepository;
    @Autowired
    ViolationListRepository violationListRepository;
    @Autowired
    SystemSmsRepository systemSmsRepository;

    /**
     * 检查token失效，修改设置状态，用户检测在线人数
     * <p>
     * 不在方法内使用线程，防止JPA线程发生阻塞造成无法修改信息
     */
    @Scheduled(fixedRate = 1000)
    public void tokenScheduled() {
        List<TokenList> allToken = tokenListRepository.findAllByStatus(0);
        if (allToken != null || allToken.size() > 0) {
            allToken.forEach((item) -> {
                item.setUnTime(item.getUnTime() - 1000);
                if (item.getUnTime() <= 0) {
                    //如果token时间失效，软删除设置状态为1
                    item.setStatus(1);
                }
                tokenListRepository.save(item);
            });
        }
    }

    /**
     * 检测用户预约到期时间
     * <p>
     * 不在方法内使用线程，防止JPA线程发生阻塞造成无法修改信息
     */
    @Scheduled(fixedRate = 1000)
    public void reserScheduled() {
        //查找预约状态为0的预约消息
        List<ReserUserInfo> allReser = reserUserInfoRepository.findAllByStatus(0);
        if (allReser != null || allReser.size() > 0) {
            allReser.forEach((item) -> {
                long reserListId = item.getReserListId();
                //获取该预约的生效时间段
                Optional<ReserList> byId = reserListRepository.findById(reserListId);
                if (byId.isPresent()) {
                    ReserList reserList = byId.get();
                    String openTime = reserList.getOpenTime();
                    String[] split = openTime.split("-");
                    boolean dateVer = DateUtil.dateVer(split[0], split[1]);
                    //如果时间不通过，修改状态，并向用户发送消息
                    long libraryId = item.getLibraryId();
                    Optional<LibraryList> libraryListOptional = libraryListRepository.findById(libraryId);
                    Optional<User> userOptional = userRepository.findById(item.getUserId());
                    if (!dateVer && libraryListOptional.isPresent() && userOptional.isPresent()) {
                        LibraryList libraryList = libraryListOptional.get();
                        User user = userOptional.get();
                        //为可预约人数加一
                        reserList.setNowPeople(reserList.getNowPeople() - 1);
                        reserListRepository.save(reserList);
                        item.setStatus(1);
                        reserUserInfoRepository.save(item);
                        UserSmsList userSmsList = new UserSmsList();
                        //向用户发送消息
                        String content = "亲爱的 " + user.getName() + " ,您已超时被扣 10 分，请离开座位";
                        userSmsList.setStatus(0);
                        userSmsList.setUserId(item.getUserId());
                        userSmsList.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        userSmsList.setImg(libraryList.getImg());
                        userSmsList.setContent(content);
                        userSmsListRepository.save(userSmsList);
                        user.setScope(user.getScope() - 10);
                        userRepository.save(user);
                        String violationStr = "有个倒霉蛋被扣分了，他的userId是：" + user.getId();
                        log.info(violationStr);
                        //保存违规记录
                        ViolationList violationList = new ViolationList();
                        violationList.setUserId(user.getId());
                        violationList.setContent(violationStr + ";消息是:" + content);
                        violationList.setAvatar(user.getAvatar());
                        violationList.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        violationListRepository.save(violationList);
                    }
                }
            });
        }
    }

    /**
     * 用户积分重置为100分
     * <p>
     * 每个月早上八点整开始
     * <p>
     * 执行 hql：UPDATE User u set u.scope=100
     * <p>
     * cron表达式：0 0 8 1 * ? *
     * <p>
     * 不在方法内使用线程，防止JPA线程发生阻塞造成无法修改信息
     */
    @Scheduled(cron = "0 0 8 1 * ?")
    public void userScopeResetScheduled() {
        userRepository.updateAllUserScope();
        SystemSms systemSms = new SystemSms();
        systemSms.setContent("月初重置积分为100");
        systemSmsRepository.save(systemSms);
    }
}
